<?php
/**
 * 用户相关
 * User.class.php
 *
 * @author: camfee <camfee@foxmail.com>
 */

namespace Center;

use Common\Bridge;
use Common\ModuleBase;
use Common\PathConst;
use Common\PhotoImage;
use Common\ResourcePathManager;
use Common\Upload;

class User extends ModuleBase
{
    const FIELD_USER_ID = 'UserId';
    const FIELD_CITY_ID = 'CityId';
    const FIELD_CITY_NAME = 'CityName';
    const FIELD_USER_NICK = 'UserNick';
    const FIELD_REAL_NAME = 'RealName';
    const FIELD_ID_CODE = 'IdCode';
    const FIELD_SEX = 'Sex';
    const FIELD_HEAD_URL = 'HeadUrl';
    const FIELD_MOBILE = 'Mobile';
    const FIELD_BIRTHDAY = 'BirthDay';
    const FIELD_J_COIN = 'JCoin';
    const FIELD_INVITE_KEY = 'InviteKey';
    const FIELD_INVITE_COIN = 'InviteCoin';
    const FIELD_LOGIN_COUNT = 'LoginCount';
    const FIELD_LOGIN_TIME = 'LoginTime';
    const FIELD_IS_SHOP = 'IsShop';
    const FIELD_SHOP_ID = 'ShopId';
    const FIELD_CREATE_TIME = 'CreateTime';
    const FIELD_UPDATE_TIME = 'UpdateTime';

    /**
     * 性别: 1 男，2 女
     */
    const SEX_MAN = 1;
    const SEX_FEMALE = 2;

    protected static $_conf = [
        'db' => [
            'w' => Bridge::DB_USER_W,
            'r' => Bridge::DB_USER_R
        ],
        'table' => 'User',
        'fields' => [
            self::FIELD_USER_ID => self::VAR_TYPE_KEY,
            self::FIELD_CITY_ID => self::VAR_TYPE_INT,
            self::FIELD_CITY_NAME => self::VAR_TYPE_STRING,
            self::FIELD_USER_NICK => self::VAR_TYPE_STRING,
            self::FIELD_REAL_NAME => self::VAR_TYPE_STRING,
            self::FIELD_ID_CODE => self::VAR_TYPE_STRING,
            self::FIELD_SEX => self::VAR_TYPE_INT,
            self::FIELD_HEAD_URL => self::VAR_TYPE_STRING,
            self::FIELD_MOBILE => self::VAR_TYPE_STRING,
            self::FIELD_BIRTHDAY => self::VAR_TYPE_STRING,
            self::FIELD_J_COIN => self::VAR_TYPE_INT,
            self::FIELD_INVITE_KEY => self::VAR_TYPE_STRING,
            self::FIELD_INVITE_COIN => self::VAR_TYPE_INT,
            self::FIELD_LOGIN_COUNT => self::VAR_TYPE_INT,
            self::FIELD_LOGIN_TIME => self::VAR_TYPE_STRING,
            self::FIELD_IS_SHOP => self::VAR_TYPE_INT,
            self::FIELD_SHOP_ID => self::VAR_TYPE_INT,
            self::FIELD_CREATE_TIME => self::VAR_TYPE_STRING,
            self::FIELD_UPDATE_TIME => self::VAR_TYPE_STRING,
        ],
        'mc' => Bridge::MEMCACHE_DEFAULT,
        'mckey' => 'CUser:%d',
        'mctime' => 86400
    ];

    /**
     * @see ModuleBase::add() 新增
     * @see ModuleBase::update() 更新
     * @see ModuleBase::getInfoByIds() 按id查询
     * @see ModuleBase::getList() 条件查询
     * @see ModuleBase::delete() 删除
     */

    /**
     * 更新用户金果数量
     *
     * @param int $uid 用户id
     * @param int $num 改变金果数量
     * @return bool
     */
    public static function updateJCoin($uid, $num)
    {
        $data[self::FIELD_J_COIN] = [self::FIELD_J_COIN, '+' . $num];

        return self::update($uid, $data);
    }

    /**
     * 获取单个用户信息
     *
     * @param int $uid 用户id
     * @param int $num 改变金果数量
     * @return bool
     */
    public static function getUserById($uid)
    {
        $where = [
            'UserId' => $uid
        ];
        $data = self::getList($where, 0, 1);

        return !empty($data['data'][0]) ? $data['data'][0] : [];
    }

    /**
     * 抓取网络URl
     *
     * @param $userId
     * @param $url
     * @return bool|string
     */
    public static function crawlHeadUrl($userId, $url)
    {
        $ch = curl_init();
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $content = curl_exec($ch);

        $info = curl_getinfo($ch);
        curl_close($ch);

        if ($info['http_code'] == 200) {
            static $MAX_AVATAR_SIZE = 2097152; // 2M

            // 限定图片最大体积
            if ($info['size_download'] <= $MAX_AVATAR_SIZE) {
                $filename = tempnam(ini_get('upload_tmp_dir'), 'avatar');

                $result = file_put_contents($filename, $content);
                if (!$result) {
                    debug_log("crawlHeadUrl failed, userId:{$userId}, url:{$url}");

                    return false;
                }

                return static::saveHeadUrl($userId, $filename);
            }
        }

        return false;
    }

    /**
     *  获取头像的链接地址
     *
     * @param int $userId 用户ID
     * @param     $image_status
     * @return string
     */
    public static function saveHeadUrl($userId, $image_status)
    {
        $img_url = Upload::saveImg(PathConst::IMG_HEAD, $image_status, PathConst::IMG_HEAD_SIZE, $userId);
        if (empty($img_url)) {
            debug_log("getHeadUrl failed, {$userId}", JF_LOG_WARNING);
            return false;
        }

        return $img_url;
    }
}
